<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-03 21:11:06
 * @Last Modified time: 2023-02-13 11:06:41
 */
namespace app\api\services\store;

use app\common\services\store\GoodsService as CommonGoodsService;
use app\common\services\store\CartService;
use app\common\services\store\GoodsSpecService;
use app\common\services\store\GoodsCollectionService;
use frank\utils\helper\ArrayHelper;
use frank\services\CacheService;

/**
 * 
 * Class GoodsService
 */
class GoodsService extends CommonGoodsService
{
    /**
     * 获取列表 api
     */
    public function getApiGoodsList(array $params,$user)
    {
        [$page, $limit] = $this->getPageValue();
        $where = $this->getParamWhere($params);
        $list = $this->dao->getGoodsListAsWith($where,$page, $limit,['id','goods_name','goods_imgs','sales_initial','sales_actual','spec_type'],['sku']);
        $cartService = CartService::instance()->init($user); 
        foreach ($list as &$item) {
        	$item['goods_cart_count'] = $cartService->getGoodsNum((int)$item['id']);
        	$item['goods_sku_id'] = $item['spec_type']['value'] == 1? $item['sku'][0]['id'] : 0;
        }
        return $list->hidden(['sku']);
    }

     /**
     * 获取商品详情页面 
     */
    public function getApiDetails($gid, $user = false)
    {

        $detail = $this->getCacheDetail($gid);


        $cartCount = CartService::instance()->init($user)->getGoodsNum($gid);

        // 用户收藏状态
        $GoodsCollectin = $user ? GoodsCollectionService::instance()->status($gid,$user['id']) : 0;
        return [
            'goods'=>$detail,
            'goods_collectin'=>$GoodsCollectin,
            'goods_cart_count'=>$cartCount
        ];
    }


    /**
     * 获取商品规格
     */
    public function getDetailSku($gid, $user = false){
        $filter['id'] = $gid;
        $filter['delete_time'] = 0;
        // 获取商品详情
        $detail = $this->dao->search(['id'=>$gid])->with(['sku'])->field('id,goods_imgs,buy_limit_status,buy_limit,buy_least_status,buy_least,goods_status,spec_type')->find();
        $this->checkGoods($detail);
        $spec_list = [];
        if($detail['spec_type']['value'] == 2){
            $spec_list = GoodsSpecService::instance()->getGoodsSpecData($detail['id']);
        }
        $skus = is_object($detail['sku']) ? $detail['sku']->toArray() : $detail['sku'];
        $sku = ArrayHelper::getArrayMinItem($skus,'price');
        $goods_cart_count = CartService::instance()->init($user)->getGoodsNum($gid);
        return compact('detail','spec_list','sku','goods_cart_count');
    }

}